﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using DG.Tweening;

public class PhonicsLetterItem : MonoBehaviour, IPointerClickHandler {
    
    public MeshRenderer mr;

    private GameObject buyIcon;
    public Transform btn_ads;

    private bool isClick = false;

    //是否购买  
    public bool isBuy = true;
    public bool isPlayAds;

    public int index;

    private string l;

    PhonicsLetterPanel phonicsLetterPanel;

    public Material material;

    //public bool isFinshCurGame = false;

    // Use this for initialization
    void Awake () {
        //miniEvent.SetUIEvent (enUIEventType.Click, enUIEventID.Phonics_Letter_Click, new stUIEventParams() {argInt = index});
        rotationOrg = transform.localEulerAngles;
    }
    
	public void Change(int t, PhonicsLetterPanel plp) {
		this.index = t;
		 l = ((char)t).ToString ();
        material = ResourceManager.Instance.GetResource ("study_phonics/study_phonics_material/303010503_" + l, typeof(Material), enResourceType.Prefab, true).m_content as Material;
		mr.material = material;
        material.shader = Shader.Find("Unlit/Transparent");
        isClick = false;
        if (l == "A")
            material.shader = Shader.Find("Unlit/Transparent");
        else
        {
            if (!StudyPhonicsManager.Instance.IsOverCurLevel(this.index))
                material.shader = Shader.Find("Unlit/Transparent Color");
            else
                material.shader = Shader.Find("Unlit/Transparent");
        }

        phonicsLetterPanel = plp;
        //Debug.LogError(isBuy.ToString() + "   ==  " + l);
        isBuy = PayManager.Instance.IsBuyItem((int)MainItemEnum.StudyPhonics);
        if (l == "A" || l == "B" || l == "C"/* && l != "D"*/)
        {
            isBuy = true;
        }
        Transform icon = transform.Find("shopCar");
        if (icon != null)
        {
            buyIcon = icon.gameObject;
            buyIcon.SetActive(!isBuy);
        }
        isPlayAds = false;
        if (l == "D")
        {
            buyIcon.SetActive(false);
#if UNITY_IOS
            if (!isBuy)
            {
                StudyEnglishProgressInfo info = LocalDataManager.Instance.Load<StudyEnglishProgressInfo>(ELocalDataType.StudyEnglishGame);
                if (info.zrpd_adsCount == 0)
                {
                    if (AdsManager.Instance.AdsReady(AdsNameConst.Ads_English))
                    {
                        btn_ads = transform.FindChildEx("btn_ads");
                        if (btn_ads != null)
                        {
                            isPlayAds = true;
                            btn_ads.gameObject.SetActive(true);
                            EventBus.Instance.RemoveEventHandler<string>(EventID.ADS_DONE_CALLBACK, OnAdsCallback);
                            EventBus.Instance.AddEventHandler<string>(EventID.ADS_DONE_CALLBACK, OnAdsCallback);
                        }
                    }

                }
            }
#endif
            isBuy = true;
        }
    }

    private void OnAdsCallback(string adsName)
    {
        if (btn_ads == null || !btn_ads.gameObject.activeSelf)
        {
            EventBus.Instance.RemoveEventHandler<string>(EventID.ADS_DONE_CALLBACK, OnAdsCallback);
            return;
        }
        if (adsName == AdsNameConst.Ads_English.Name)
        {
            EventBus.Instance.RemoveEventHandler<string>(EventID.ADS_DONE_CALLBACK, OnAdsCallback);
            btn_ads.gameObject.SetActive(false);
            StudyEnglishProgressInfo info = LocalDataManager.Instance.Load<StudyEnglishProgressInfo>(ELocalDataType.StudyEnglishGame);
            info.zrpd_adsCount++;
            LocalDataManager.Instance.Save(ELocalDataType.StudyEnglishGame, info);
            isClick = false;
            isPlayAds = false;
        }
    }

    public void SetBuyIconState(bool isActive)
    {    
        if(l != "A" && l != "B" && l != "C" && l != "D" && buyIcon != null)
            buyIcon.SetActive(isActive);
    }


    public void OnPointerClick (PointerEventData eventData){
		Debug.LogError ("click letter " + ((char)index).ToString ());
        if (isClick)
        {
            return;
        }

        if (isPlayAds)
        {
            isClick = true;

            TopNoticeManager.Instance.ShowOkTip(StudyPhonicsManager.ADS_TIPS, () =>
            {
                if (AdsManager.Instance.AdsReady(AdsNameConst.Ads_English))
                {
                    AdsManager.Instance.ShowAds(AdsNameConst.Ads_English);
                }
                else
                {
                    Debug.Log("广告还未准备好. name:" + AdsNameConst.Ads_English.Name);
                    isClick = false;
                }
            },()=> {
                isClick = false;
            });
            return;
        }

        isBuy = PayManager.Instance.IsBuyItem((int)MainItemEnum.StudyPhonics);
        if (!isBuy && l != "A" && l != "B" && l != "C" && l != "D")
        {
            //调用购买
            PayManager.Instance.Pay((int)MainItemEnum.StudyPhonics, (id, suc) =>
            {
                Debug.Log(id + "," + suc);
                if (id == (int)MainItemEnum.StudyPhonics && suc)
                {
                    isBuy = true;
                    phonicsLetterPanel.SetBuyIconState(false);
                }
            }, true, AdsNameConst.Ads_English);
            return;
        }

        if (index != StudyPhonicsManager.Instance.StartIndex)
        {
            //检测上一关是否过了，按照顺序过关
            if (!StudyPhonicsManager.Instance.IsOverCurLevel(index - 1))
            {
                //play-sound  “还没有学到这里，请按照顺序学习”。
                AudioManager.Instance.PlaySound(Itempathinfo.PhonicEggGamePath + "603010709");
                phonicsLetterPanel.ShakeZm();
                return;
            }
        }
        //Debug.Log("index === " + index);

        StudyPhonicsManager.Instance.isTurnLeDi = true;
        isClick = true;
        EventBus.Instance.BroadCastEvent<string>(EventID.GUIDAO_MOVE, this.l);
        Invoke("BroadCastEvent", 0.4f);
        AudioManager.Instance.PlaySound(Itempathinfo.PhonicEggGamePath + "603010703");
	}

    void BroadCastEvent() {
        isClick = false;
        EventBus.Instance.BroadCastEvent<int>(EventID.PHONICS_CLICK_LETTER, this.index);
        EventBus.Instance.BroadCastEvent<bool>(EventID.SET_ZHUANPAN_ACTIVE, false);
    }


    Vector3 rotationOrg;
    Tweener tweener;
    public void ShakeZm()
    {
        //phonicsLetterPanel.ShakeStrength;
        if (tweener != null && tweener.IsPlaying()) return;
        
        transform.localEulerAngles = new Vector3(rotationOrg.x, rotationOrg.y, rotationOrg.z + phonicsLetterPanel.ShakeStrength);
        Vector3 target = new Vector3(rotationOrg.x, rotationOrg.y, rotationOrg.z - phonicsLetterPanel.ShakeStrength);
        tweener = transform.DOLocalRotate(target, 0.2f).SetEase(Ease.Linear).SetLoops(-1, LoopType.Yoyo);
        TimerManager.Instance.AddTimer(0.8f, () =>
        {
            transform.localEulerAngles = rotationOrg;
            transform.DOKill();
        });
    }


}
